// 画板主逻辑App类，按ES module导出
// 只保留App类和必要工具函数，兼容uniapp
// ... 迁移原circuitApp.js所有核心逻辑

import { ACContactor,ACContactor2,ACContactorClose,ACContactorClose2,
ACContactorOpen,ACContactorOpen2,ammeter,asw1,asw2,asw3,asyncMotor,bulb,buzzer,compoundButton,compoundButtonRed,currentTransformer,fuse1,fuse2,fuse3,ledTube,meter,motor,pilotLampBlue,pilotLampGreen,pilotLampRed,pilotLampWhite,pilotLampYellow,power1,power2,power3,power4,protector2,selfLockButton,selfLockButtonRed,socket,stopButton,sw1,sw2,sw3,sw4,sw5,sw6,terminalHorizontal,terminalVertical,thermalRelay } from './circuitComponents';
export class App {
  constructor({ canvas, ctx, dpr, baseScale }) {
    this.canvas = canvas;
    this.ctx = ctx;
    this.dpr = dpr;
    this.baseScale = baseScale;
    this.components = [];
    this.nodes = [];
    this.protectorComponents = [];
    this.renderCallback = null;
    this.onLineChangeCallback = null;
    this.isScaleChange = false;
    this.viewScale = 1;
    this.showMagnifier = false;
    this.lines = [];
    this.undoLines = [];
  }

  addComponent(t) {
    // 这里假设你已经有了所有元件类的定义，如 Bulb, LedTube, Sw1, Sw2, ... 等
    let CompClass = BaseComponent; // 默认元件基类

    // 根据 type 选择不同的元件类
    if (t.type === 'bulb' || t.type === 'ledTube' || t.type.includes('pilotLamp')) {
      CompClass = bulb;
    } else if (t.type === 'buzzer') {
      CompClass = Buzzer;
    } else if (t.type === 'terminalHorizontal') {
      CompClass = TerminalHorizontal;
    } else if (t.type === 'terminalVertical') {
      CompClass = TerminalVertical;
    } else if (t.type === 'sw1') {
      CompClass = sw1;
    } else if (t.type === 'sw2') {
      CompClass = sw2;
    } else if (t.type === 'sw3') {
      CompClass = sw3;
    } else if (t.type === 'sw4') {
      CompClass = sw4;
    } else if (t.type === 'sw5') {
      CompClass = sw5;
    } else if (t.type === 'sw6') {
      CompClass = sw6;
    } else if (t.type === 'socket') {
      CompClass = socket;
    } else if (t.type === 'asw1') {
      CompClass = asw1;
    } else if (t.type.includes('protector')) {
      CompClass = protector2;
    } else if (t.type.includes('fuse')) {
      CompClass = fuse3;
    } else if (t.type === 'meter') {
      CompClass = meter;
    } else if (t.type === 'motor') {
      CompClass = motor;
    } else if (t.type === 'asyncMotor') {
      CompClass = asyncMotor;
    } else if (t.type === 'stopButton') {
      CompClass = stopButton;
    } else if (t.type.includes('selfLockButton')) {
      CompClass = selfLockButton;
    } else if (t.type.includes('compoundButton')) {
      CompClass = compoundButton;
    } else if (t.type === 'ACContactorOpen') {
      CompClass = ACContactorOpen;
    } else if (t.type === 'ACContactorOpen2') {
      CompClass = ACContactorOpen2;
    } else if (t.type === 'ACContactorClose') {
      CompClass = ACContactorClose;
    } else if (t.type === 'ACContactorClose2') {
      CompClass = ACContactorClose2;
    } else if (t.type === 'ACContactor') {
      CompClass = ACContactor;
    } else if (t.type === 'ACContactor2') {
      CompClass = ACContactor2;
    } else if (t.type === 'thermalRelay') {
      CompClass = thermalRelay;
    } else if (t.type === 'ammeter') {
      CompClass = ammeter;
    } else if (t.type === 'currentTransformer') {
      CompClass = currentTransformer;
    }

    // 实例化元件
    const comp = new CompClass({
      ...t,
      app: this, // 传递 app 实例
      canvas: this.canvas,
    });

    // 如果是保护器，加入保护器列表
    if (t.type && t.type.includes('protector')) {
      this.protectorComponents.push(comp);
    }

    // 加入元件和节点
    this.components.push(comp);
    this.nodes.push(...comp.nodes);
  }

  setMagnifier({ canvas, ctx }) {
    this.magnifierOptions = { canvas, ctx };
  }
  renderMagnifier(t) {
    const { x, y } = this.getPhysicalPos(t);
    const { canvas, ctx } = this.magnifierOptions || {};
    if (!canvas || !ctx) return;
    const n = canvas.width, a = canvas.width;
    const o = x * this.dpr, r = y * this.dpr;
    const c = this.ctx.getImageData(o - n / 2, r - a / 2, n, a);
    ctx.clearRect(0, 0, n, a);
    ctx.putImageData(c, 0, 0);
    this.showMagnifier = true;
  }
  hideMagnifier() {
    const { canvas, ctx } = this.magnifierOptions || {};
    if (canvas && ctx) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      this.showMagnifier = false;
    }
  }
  // 注册渲染回调
  onRender(cb) {
    this.renderCallback = cb;
  }

  // 注册连线变化回调
  onLineChange(cb) {
    this.onLineChangeCallback = cb;
  }

  render() {
    // ... existing render logic ...
    if (this.renderCallback) {
      this.renderCallback();
    }
  }
} 

class BaseComponent {
  constructor({ app, type, name, x, y, width, height, images, nodes, isActive = false }) {
    console.log(app, 'app');
    this.app = app;
    this.type = type;
    this.name = name;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.images = [];
    this.activeImg = null;
    this.isActive = isActive;
    // 节点对象数组，每个节点会被包装成 Node 类
    this.nodes = nodes.map(node =>
      new Node({
        ...node,
        comp: this,
        app: app,
      })
    );
    this.loadImage(images);

    console.log('this.app:', this.app);
    console.log('this.app.canvas:', this.app && this.app.canvas);
    console.log('typeof this.app.canvas.createImage:', typeof (this.app && this.app.canvas && this.app.canvas.createImage));
  }
  // 加载图片
  loadImage(images) {
    images.forEach((src, idx) => {
      const img = this.app.canvas.createImage();
      img.src = src;
      img.onload = () => {
        this.images[idx] = img;
        if (idx === 0) {
          this.activeImg = img;
          this.app.render();
        }
      };
    });
  }
  // 节点状态变化（可被子类重写）
  nodeStatusChange() {}
  // 绘制元件
  draw(ctx) {
    if (this.isActive) {
      ctx.save();
      ctx.strokeStyle = "red";
      ctx.lineWidth = 3;
      ctx.setLineDash([5, 3]);
      ctx.strokeRect(this.x - 5, this.y - 5, this.width + 10, this.height + 10);
      ctx.restore();
    }
    if (this.activeImg) {
      ctx.drawImage(this.activeImg, this.x, this.y, this.width, this.height);
    }
    this.nodes.forEach(node => node.draw(ctx));
  }
  // 判断是否被点击
  isClicked(x, y) {
    return (
      x >= this.x &&
      x <= this.x + this.width &&
      y >= this.y &&
      y <= this.y + this.height
    );
  }
  // 点击事件（可被子类重写）
  onClick(e) {
    console.log(`${this.name} clicked`);
  }
}

// 节点类（Node）
class Node {
  constructor({ dx, dy, status = '', comp, app, canvas }) {
    this.dx = dx;
    this.dy = dy;
    this.radius = 6;
    this.status = status;
    this.siblings = [];
    this.comp = comp;
    this.app = app;
    this.canvas = canvas;
  }
  get x() {
    return this.comp.x + this.dx;
  }
  get y() {
    return this.comp.y + this.dy;
  }
  removeSibling(node) {
    const idx = this.siblings.findIndex(s => s === node);
    if (idx !== -1) this.siblings.splice(idx, 1);
    const idx2 = node.siblings.findIndex(t => t === this);
    if (idx2 !== -1) node.siblings.splice(idx2, 1);
  }
  addSibling(node, { isClickSw, isOneway = false } = {}) {
    if (this.status && node.status && this.status !== node.status) {
      if (this.comp.type === 'currentTransformer' && this === this.comp.nodes[3]) return;
      if (node.comp.type === 'currentTransformer' && node === node.comp.nodes[3]) return;
      this.app.onError && this.app.onError({ comp: this.comp, message: '短路' });
      if (!isClickSw) return;
    }
    this.siblings.push(node);
    if (!isOneway) node.siblings.push(this);
    if (!this.status && node.status) this.setStatus(node.status);
    if (this.status && !node.status) node.setStatus(this.status);
  }
  setStatus(status) {
    this.status = status;
    this.comp.nodeStatusChange && this.comp.nodeStatusChange();
    if (status) {
      this.siblings.forEach(s => {
        if (s.status !== this.status) {
          if (s.status && this.status) {
            this.app.onError && this.app.onError({ comp: this.comp, message: '短路' });
            return;
          }
          s.setStatus(status);
        }
      });
    }
  }
  draw(ctx) {
    // 可自定义节点渲染
  }
  isHit(x, y) {
    return Math.hypot(x - this.x, y - this.y);
  }
}

export { BaseComponent, Node };